#include "sqlist.h"
#include <stdlib.h>
#include <stdio.h>
#include "printelem.h"

void initSqList(SQList *L)
{
    if (L == NULL)
        return;

    L->size = MAXSIZE;
    L->datas = (ElemType *)malloc(sizeof(ElemType) * L->size);
    L->length = 0;
}

void destroySqList(SQList *L)
{
    if (L == NULL)
        return;
    free(L->datas);
    L->datas = NULL;
    L->size = 0;
    L->length = 0;
}

void clearSqList(SQList *L)
{
    if (L == NULL)
        return;

    L->length = 0;
}

int sqListEmpty(SQList *L)
{
    if (L == NULL)
        return 1;

    return L->length == 0 ? 1 : 0;
}

int sqListLength(SQList *L)
{
    if (L == NULL)
        return 0;

    return L->length;
}

int getSqListElem(SQList *L, int i, ElemType *e)
{
    if (L == NULL || i < 0 || i >= L->length)
        return 0;

    *e = L->datas[i];
    return 1;
}

int locateSqListElem(SQList *L, ElemType e)
{
    if (L == NULL)
        return -1;

    int i = 0;
    while (i < L->length)
    {
        if (L->datas[i] == e)
            return i;
    }

    return -1;
}

int priorSqListElem(SQList *L, ElemType cur_e, ElemType *pre_e)
{
    int result = locateSqListElem(L, cur_e);
    if (result <= 0)
        return 0;

    *pre_e = L->datas[result - 1];
    return 1;
}

int nextSqListElem(SQList *L, ElemType cur_e, ElemType *next_e)
{
    int result = locateSqListElem(L, cur_e);
    if (result == -1 || result == L->length - 1)
        return 0;

    *next_e = L->datas[result + 1];
    return 1;
}

int insertSqList(SQList *L, int i, ElemType e)
{
    if (L == NULL || i < 0 || i > L->length || L->length >= L->size)
        return 0;
    
    int j;
    for (j = L->length; j > i; j--)
    {
        L->datas[j] = L->datas[j - 1];
    }
   
    L->datas[i] = e;
    L->length++;
    return 1;
}

int deleteSqList(SQList *L, int i, ElemType *e)
{
    if (L == NULL || i < 0 || i >= L->length)
        return 0;

    *e = L->datas[i];

    int j;
    for (j = i; j < L->length - 1; j++)
    {
        L->datas[j] = L->datas[j + 1];
    }
    L->length--;
    return 1;
}

void traverseSqList(SQList *L)
{
    int i;
    for (i = 0; i < L->length; i++)
    {
        printInt(L->datas[i]);
        printf("\t");
    }
    printf("\n");
}
